package com.example.localareanetworkchat.fragment.home

import android.app.AlertDialog
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.widget.Toolbar
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.localareanetworkchat.R
import com.example.localareanetworkchat.fragment.MainViewModel
import com.example.localareanetworkchat.fragment.home.adapter.ChatGroupListAdapter
import com.example.localareanetworkchat.persistence.entity.ChatGroup
import com.example.localareanetworkchat.persistence.entity.GroupAddType
import com.google.android.material.bottomnavigation.BottomNavigationView
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.*


class HomeFragment : Fragment() {

    val TAG = HomeFragment::class.simpleName

    private var viewModel: MainViewModel ?= null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_home, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        viewModel = ViewModelProvider(requireActivity(), ViewModelProvider.AndroidViewModelFactory(requireActivity().application)).get(
            MainViewModel::class.java)
        val user = viewModel?.user
        requireActivity().findViewById<Toolbar>(R.id.toolbar).title = user?.name
        requireActivity().findViewById<BottomNavigationView>(R.id.bnv_chat_main).visibility = View.VISIBLE
        requireActivity().findViewById<Toolbar>(R.id.toolbar).menu.clear()
        requireActivity().findViewById<Toolbar>(R.id.toolbar).navigationIcon = null

        fab_chat_home_add.setOnClickListener{ v ->
            val popupMenu = PopupMenu(requireContext(), v)
            popupMenu.setOnMenuItemClickListener {
                when(it.itemId){
                    R.id.menu_item_chat_home_add_join_group -> {

                        if (viewModel?.getNetStatus() != 1 && viewModel?.getNetStatus() != 3){
                            AlertDialog.Builder(requireContext()).setMessage("请先切换到WiFi网络").show()
                        } else {
                            val dialogBuilder = AlertDialog.Builder(requireContext())
                            val dialogView = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_join_chat_group, null)
                            dialogBuilder.setView(dialogView)
                            val cancelBtn: Button = dialogView.findViewById(R.id.btn_chat_home_join_group_cancel)
                            val okBtn: Button = dialogView.findViewById(R.id.btn_chat_home_join_group_ok)

                            val dialog = dialogBuilder.show()

                            okBtn.setOnClickListener {
                                Log.i(TAG, "onActivityCreated: " + "join group")
                                val etGroupJoinAddress: EditText = dialogView.findViewById(R.id.et_chat_home_join_group_address)
                                val etGroupJoinAddressSelf: EditText = dialogView.findViewById(R.id.et_chat_home_join_group_address_self)
                                val etGroupInvitationCode: EditText = dialogView.findViewById(R.id.et_chat_home_join_group_invitation_code)

                                viewModel?.joinGroup(user!!, etGroupJoinAddress.text.toString(), etGroupJoinAddressSelf.text.toString(), etGroupInvitationCode.text.toString())
                                dialog.dismiss()
                            }

                            cancelBtn.setOnClickListener {
                                dialog.dismiss()
                            }

                        }

                        true
                    }
                    R.id.menu_item_chat_home_add_create_group -> {

                        if (viewModel?.getNetStatus() != 1 && viewModel?.getNetStatus() != 3){
                            AlertDialog.Builder(requireContext()).setMessage("请先切换到WiFi网络").show()
                        }else {
                            val dialogBuilder = AlertDialog.Builder(requireContext())
                            val dialogView = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_create_chat_group, null)
                            dialogBuilder.setView(dialogView)
                            dialogBuilder.setCancelable(true)

                            val cancelBtn: Button = dialogView.findViewById(R.id.btn_chat_home_create_group_cancel)
                            val okBtn: Button = dialogView.findViewById(R.id.btn_chat_home_create_group_ok)

                            val etGroupName: EditText = dialogView.findViewById(R.id.et_chat_home_create_group_name)
                            val etGroupJoinAddress: EditText = dialogView.findViewById(R.id.et_chat_home_create_group_address)
                            val tvGroupInvitationCode: TextView = dialogView.findViewById(R.id.tv_chat_home_create_group_invitation_code)

                            val invitationCode = viewModel?.generateInvitationCode()
                            tvGroupInvitationCode.text = invitationCode
                            val dialog = dialogBuilder.show()
                            okBtn.setOnClickListener {
                                val groupName = etGroupName.text.toString()
                                lifecycleScope.launch(Dispatchers.IO) {
                                    if (viewModel?.checkDuplicatedGroupName(groupName) == true){
                                        lifecycleScope.launch(Dispatchers.Main){
                                            Toast.makeText(requireContext(), "群组名已存在", Toast.LENGTH_SHORT).show()
                                        }
                                        return@launch
                                    }else {
                                        viewModel?.insertChatGroup(
                                            // joinAddress 替换为实际获取的 ip 即可
                                            ChatGroup(0, groupName, user!!.id,  user.uid, UUID.randomUUID().toString(), invitationCode!!, "", GroupAddType.GROUP_ADD_TYPE_CREATE, etGroupJoinAddress.text.toString(),
                                            DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss").format(
                                                LocalDateTime.now()), "", 0), user
                                        )
                                        lifecycleScope.launch(Dispatchers.Main){
                                            Toast.makeText(requireContext(), "群组：$groupName 创建成功", Toast.LENGTH_SHORT).show()
                                            dialog.dismiss()
                                        }
                                    }

                                }
                            }

                            cancelBtn.setOnClickListener {
                                dialog.dismiss()
                            }
                        }
                        true
                    }
                    else -> {
                        true
                    }
                }
            }
            popupMenu.inflate(R.menu.menu_chat_home_add)
            popupMenu.show()
        }

        rv_chat_home_group_list.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        val groupChatListAdapter = ChatGroupListAdapter(requireContext(), viewModel!!)
        rv_chat_home_group_list.adapter = groupChatListAdapter

        viewModel?.queryAllChatGroupByUserId(user!!.id)?.observe(requireActivity(), {
            Log.i(TAG, "group size: ${it.size}")
            groupChatListAdapter.submitList(it)
        })
    }

}